package com.android.publicModule.webview.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 数据库helper类
 * @author Administrator
 *
 */
public class DBOpenHelper extends SQLiteOpenHelper {
	private static final String DBNAME = "webview.db";
	public static final String URL_INFO_TABLE = "UrlInfo";
	private static final int VERSION = 1;
	private static DBOpenHelper openHelper;
	public DBOpenHelper(Context context) {
		super(context, DBNAME, null, VERSION);
	}
	
	public static DBOpenHelper getInstance(Context context) {
		if(openHelper==null)
		{
			openHelper = new DBOpenHelper(context.getApplicationContext());
		}
		return openHelper;
	}

	/**
	 * 创建数据库表
	 */
	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE IF NOT EXISTS "+URL_INFO_TABLE+" (" +
				"id INTEGER PRIMARY KEY AUTOINCREMENT,"+
				"url VARCHAR(2000) NOT NULL," +
				"getData VARCHAR(2000)," +
				"headers VARCHAR(2000)," +
				"cacheType INTEGER DEFAULT 0," +
				"savePath VARCHAR(200)," +
				"lastUpdateMinute INTEGER DEFAULT 0," +
				"updateIntervalMinute INTEGER DEFAULT 0," +
				"time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
	}

	/**
	 * 升级数据库
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS "+URL_INFO_TABLE);
		onCreate(db);
	}
	
	int index = 0;
	public void OpenDB() {
		index++;
	}
	
	public void closeDB(SQLiteDatabase db) {
		if(index>1)
		{
			index--;
		}
		else
		{
			index = 0;
			if(db==null)
			{
				db = getWritableDatabase();
			}
			db.close();
			db = null;
		}
	}
	
	public void forceCloseDB() {
		index = 0;
		SQLiteDatabase db = getWritableDatabase();
		db.close();
		db = null;
	}

}
